package com.cat.dao.Impl;

import com.cat.execption.DaoExecption;
import com.cat.util.JdbcUtils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author HYC kobe524348@gmail.com
 * @program HYC_CatRecruit
 * @description
 * @date 2019-04-05 11:33
 */
abstract class AbstractDao {
    private static Connection conn = null;
    private static Statement st = null;
    private static ResultSet rs = null;

    protected static List<Object> getResultList(String sql, Class clazz) {

        System.out.println("dao.Impl.StudentDAOImpl.getResultList: " + sql);
        List<Object> datas = new ArrayList<>();

        try {
            conn = JdbcUtils.getConnection();
            st = conn.createStatement();
            rs = st.executeQuery(sql);
            ResultSetMetaData md = rs.getMetaData();
            while (rs.next()) {
                Object obj = clazz.newInstance();
                //取得JavaBean的所有构造方法
                Method[] method = clazz.getMethods();
                //取得字段数
                int colCount = md.getColumnCount();
                String[] colName = new String[colCount + 1];
                for (int i = 1; i <= colCount; i++) {
                    //取得所有的字段名
                    colName[i] = md.getColumnLabel(i);
                }
                for (int i = 1; i <= colCount; i++) {
                    //生成字段对应的set方法
                    String setMethod = "set" + colName[i];

                    for (Method ms : method) {
                        if (setMethod.equalsIgnoreCase(ms.getName())) {
                            //执行set方法

                            ms.invoke(obj, rs.getObject(colName[i]).toString());

                        }
                    }
                }
                datas.add(obj);
            }

        } catch (SQLException | IllegalAccessException | InvocationTargetException | InstantiationException e) {
            e.printStackTrace();
            throw new DaoExecption("数据库获取对象List产生异常", e);
        } finally {
            JdbcUtils.free(rs, st, conn);
        }
        return datas;
    }
}
